<?php
namespace pay;
use  think\Request;
use   think\Config;
date_default_timezone_set('PRC');
header("ontent-Type:text/html; charset=UTF-8");
class Yitianmao{

    private  $apiKey;
    private  $callback;
    private  $notify_url;
    public function __construct()
    {
            $class = strtolower("Yitianmao");

            $this->Config  = $Config = Config::get($class);
            $this->apiKey = $Config['apiKey'];

            $domain = Request::instance()->domain();
            //curl实例
            $this->http =new \http\Http();
        if(!empty($Config['callback_url'])){
            $this->callback = $Config['callback_url'];
        }else{
            $this->callback = $domain."/out/Notify/callbackurl";
        }
        if(!empty($Config['notify_url'])){
            $this->notify_url = $Config['notify_url'];
        }else{
            $this->notify_url =$domain."/out/Notify/handleyitian";
        }
    }

    //生成签名字符串
    private function Generationsign($sign){
        $Sign_last = substr(strtoupper(md5($sign)),0,16);
        return $Sign_last;
    }

    //获取处理的方法
    private function getGenerationAction($method){
            return $this->pay_action_url()[$method];
    }
    /**
     * @param $Context
     * @return mixed|string Content 处理
     */
    private function generationContext($Context){
        $Context1=base64_encode($Context);
        $Context1 = str_ireplace("+","-",$Context1);
        $Context1 = str_ireplace("/","_",$Context1);
        $Context1 = str_ireplace("=","",$Context1);
        return $Context1;
    }
    /**
     * @return string 网关支付
     */
    public function gateway_pay($amount=1,$payNo,$pay_mode=""){
                $d_time = date("YmdHis");
                $configWay = $this->getGenerationAction(__FUNCTION__);
                $sysConfig = $this->sysConfigs();//获取系统处理
                $Generationsign = $configWay['Generationsign'];

                $tdata = ["trans_time"=>$d_time,
                    "app_id"=>$payNo,
                    "callback_url"=>urlencode($this->callback),
                    "notify_url"=>urlencode($this->notify_url),
                    "amount"=>bcmul($amount,100),
                ];
                if(!empty($pay_mode)){
                    $tdata['pay_mode']  =$pay_mode;
                }
        $configWayBase=array_merge($configWay['Base'],$tdata);

        $data['context'] =  $this->generationContext(http_build_query($configWayBase));//base64之后
        $data['signature'] = $this->delwithSign($Generationsign,$configWayBase);
        $sys = array_merge($sysConfig,$data);


         $sysResult  =$this->http->post($configWay["url"],$sys);
       $sysResult = mb_convert_encoding($sysResult, "UTF-8","GBK");
        $sysResult = json_decode($sysResult,true);
        if(isset($sysResult['errorcode'])&&$sysResult['errorcode']=="0000"){
           $result =   base64_decode($this->UnPackUrlBase64($sysResult['context']));
            parse_str($result,$result);
            $result['pay_url'] = base64_decode($this->UnPackUrlBase64($result['pay_url']));

           return $result['pay_url'];
        }
        return $sysResult;

    }
    public function Notify($content){
                //加密的字符串

        $tdata = ["msg"=>"异常","status"=>0,"data"=>[]];
        parse_str($content,$result);
        $result = base64_decode($this->UnPackUrlBase64($result['context']));
        parse_str($result,$result);
        //异步流处理

        $strSign=$result["signature"]; //秘钥
        $NotifySignModel  = new \app\admin\model\UsersRecharge();
        $res = $NotifySignModel->where("thirdparty_payno",$result['trans_id'])->find();
        if($res['status']==2){
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已失效"]);
        }
        if($res['status']==1){
            return array_merge($tdata,['status'=>0,"msg"=>"该订单已充值成功"]);
        }
        $resultBa['trans_id'] =$result['trans_id'];
        $resultBa['result'] =$result['result'];
        $resultBa['amount'] =$result['amount'];
        $NotifySign = ["trans_id","result","amount"];
       $sign= $this->delwithSign($NotifySign,$resultBa);

       if($strSign==$sign){

          return  ["data"=>$result,"status"=>1,"msg"=>"验证成功"];
       }

        return $tdata;

    }

    //处理恶心的加密
    private function delwithSign($Generationsign,$configWayBase){

            $signString = [];

         array_filter($configWayBase,function($val,$key)use($Generationsign,&$signString){
                                if(in_array($key,$Generationsign)){
                                    $signString[] = "{".$val."}";
                                }
         },ARRAY_FILTER_USE_BOTH);

         if(!empty($signString)){
                array_push($signString,"{".$this->apiKey."}");
         }
        $swith = implode("|",$signString);


        $Sign = substr(strtoupper(md5($swith)),0,16);

        return $Sign;

    }

    //配置基础系统传参
    private function sysConfigs(){
        $data=array(
            "syscode"=>$this->Config['syscode'],
            "version"=>$this->Config['version'],
            "context" => "",
            "signature"=> "",
        );
        return $data;
    }

    private function pay_action_url(){
        //	$Signstr = "{" . $data["server_no"] . "}|{" . $data["trans_time"] . "}|{" .$data["account"] . "}|{" . $data["amount"] . "}|{" . $data["pay_mode"] . "}|{" . $key . "}";
        $pay_action_url=[
            "gateway_pay"=>[//支付网关配置
                "url"=>"http://www.yitianmao.com/cgi-bin/gateway_pay.cgi",
                "Generationsign"=>["server_no","trans_time","account","amount","pay_mode"],
                "Base"=>["server_no"=>100008,
                    "trans_time"=>"",
                    "account"=>$this->Config['account'],
                    "amount"=>1,
                  //  "pay_mode"=>"API_GATEWAY",
                    "pay_mode"=>$this->Config['pay_mode'],
                    "aging"=>$this->Config['aging'],
                    "app_id"=>"",
                    "callback_url"=>$this->callback,
                    "notify_url"=>$this->notify_url,
                    "memo"=>"china",
                    ]
            ],
        ];
        return $pay_action_url;
    }

    private  function UnPackUrlBase64($strdata) {
        $strdata = str_ireplace("-","+",$strdata);
        $strdata = str_ireplace("_","/",$strdata);
        while (strlen($strdata) % 4 != 0)
        {
            $strdata .= "=";
        }

        return $strdata;
    }





}
?>
